<template>
  <el-dialog
      v-model="dialogVisible"
      @open="handleDialogOpen"
      :title="currentEmployee ? '编辑员工' : '添加员工'"
      width="50%"
  >
    <el-form
        ref="formRef"
        :model="form"
        label-width="100px"
        :rules="rules"
    >
      <el-form-item label="员工账号" prop="username">
        <el-input v-model="form.username" />
      </el-form-item>

      <el-form-item label="员工姓名" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="form.sex">
          <el-radio label="男">男</el-radio>
          <el-radio label="女">女</el-radio>
          <el-radio label="其他">其他</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="form.phone" maxlength="11"/>
      </el-form-item>

      <el-form-item label="身份证号" prop="idCard">
        <el-input
            v-model="form.idNumber"
            placeholder="请输入18位身份证号"
            maxlength="18"
            show-word-limit
        />
      </el-form-item>

      <el-form-item label="初始密码" prop="password" v-if="!currentEmployee">
        <el-input v-model="form.password" show-password />
      </el-form-item>

      <el-form-item label="账号状态">
        <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="停用"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, ref, nextTick} from 'vue'
import { ElMessage } from 'element-plus'
import {addEmployee, updateEmployee} from "@/api/employee";

const formRef = ref(null)

// 对话框打开时清除验证状态,回显数据
const handleDialogOpen = () => {
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate() // 清除验证状态

      if(!props.currentEmployee){//如果时添加操作
        form.value = initForm()
      }else{
        form.value = { ...props.currentEmployee }
      }
    }
  })
}

const props = defineProps({
  modelValue: Boolean,
  currentEmployee: Object
})

const emit = defineEmits(['update:modelValue', 'refresh'])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 表单初始值
const initForm = () => ({
  username: '',
  name: '',
  phone: '',
  password: '123456',
  status: 1,
  sex: '男', // 默认值
  idNumber: ''
})

const form = ref(initForm())

// 身份证号验证函数
const validateIdCard = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入身份证号'))
  } else if (!/^\d{17}[\dXx]$/.test(value)) {
    callback(new Error('请输入有效的18位身份证号'))
  } else {
    callback()
  }
}
const rules = {
  username: [{ required: true, message: '请输入员工账号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^\d{11}$/,
      message: '请输入11位数字',
      trigger: 'blur'
    }
  ],
  password: [{ required: true, message: '请设置初始密码', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  idNumber: [
    { required: true, validator: validateIdCard, trigger: 'blur' }
  ]
}


const handleSubmit = async () => {
  try {
    await  formRef.value.validate()
    let res = null;
    //调用api
    if (props.currentEmployee) {
      res = await updateEmployee(form.value)
    } else {
      res = await addEmployee(form.value)
    }
    if(res.code === '200'){
      ElMessage.success(props.currentEmployee ? '修改成功' : '添加成功')
      emit('refresh')//告知父组件刷新列表
      dialogVisible.value = false
    }else{
      ElMessage.error(res.msg||'操作失败');
    }
    await new Promise(resolve => setTimeout(resolve, 200))
  } catch (error) {
    console.error(error)
  }
}
</script>